package utility;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Utility {

	public static int NOT_A_NUMBER = -11 ;
	private static Properties USER_PROPERTIES ; // Singleton 

	public static int getInt(String string) {
		int integer = NOT_A_NUMBER  ;
		try {
			integer = Integer.parseInt(string) ;
		}
		catch(NumberFormatException numberFormatException) {
			integer = NOT_A_NUMBER ; 
		}
		return integer ;
	}

	public static int computeTimeInSeconds(String timeString) {
		int totalTime = NOT_A_NUMBER ;
		String[] hourMinuteSeconds = timeString.split(":") ;
		int hours = 0 ; 
		int minutes = 0 ; 
		int seconds = 0 ; 
		if(hourMinuteSeconds.length == 3) { // hours exist
			hours = getInt(hourMinuteSeconds[0]) ;
			minutes = getInt(hourMinuteSeconds[1]) ; 
			seconds = getInt(hourMinuteSeconds[2]) ;
		}
		else if(hourMinuteSeconds.length == 2) {
			minutes = getInt(hourMinuteSeconds[0]) ; 
			seconds = getInt(hourMinuteSeconds[1]) ;
		}
		totalTime = seconds + minutes * 60 + hours * 60 * 60 ; 
		return totalTime ;
	}

	public static Properties getProperties() {
		// lazy initialization
		if(USER_PROPERTIES == null) {
			USER_PROPERTIES = new Properties() ;
			try {
				ClassLoader classLoader = Utility.class.getClassLoader() ;
				InputStream propertyStream = classLoader.getResourceAsStream("user.properties") ;
				if(propertyStream == null) {
					File propertyFile = new File("F:\\Programming\\Projects\\turkey-trot-display\\RunningData\\src\\user.properties") ;
					propertyStream = new FileInputStream(propertyFile) ; 
				}
				System.out.println("propertyStream: " + propertyStream) ; 
				USER_PROPERTIES.load(propertyStream) ;
				System.out.println("Loaded properties for user: " + USER_PROPERTIES.getProperty("user")) ;
			}
			catch (IOException exception) {
				System.out.println("Unable to load user properties.") ;
				exception.printStackTrace();
			}
		}
		return USER_PROPERTIES ; 
	}

}
